<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title></title>
	</head>
	<body>


		<div>連接socket地址:</div>
		<input type="text" id="ipAddress" />
		<input type="button" value="点我連接" onclick="CHAT.connection()"/>



		<div>发送消息:</div>
		<input type="text" id="msgContent"/>
		<input type="button" value="点我发送" onclick="CHAT.chat()"/>
		
		<div>接受消息：</div>
		<div id="receiveMsg" style="background-color: gainsboro;"></div>
		
		<script type="application/javascript">
			
			window.CHAT = {
				socket: null,
				init: function(ip) {
					// <!--判断浏览器是否支持 websocket-->
					if (window.WebSocket) {
						// <!--连接服务器websocket IP+端口号 ／ws是服务器WebSocketServerProtocolHandler添加的-->
						CHAT.socket = new WebSocket("ws://" + ip);
						CHAT.socket.onopen = function() {
							console.log("连接建立成功...");
						},
						CHAT.socket.onclose = function() {
							console.log("连接关闭...");
						},
						CHAT.socket.onerror = function() {
							console.log("发生错误...");
						},
						CHAT.socket.onmessage = function(e) {
							console.log("接受到消息：" + e.data);
							var receiveMsg = document.getElementById("receiveMsg");
							var html = receiveMsg.innerHTML;
							receiveMsg.innerHTML = html + "<br/>" + e.data;
							console.info("打印" + e.data);
							let obj = JSON.parse(e.data);
							if(obj.type == 1){
								// 连接成功后 每三秒像服务端发送心跳信息
								setInterval(function(){
									CHAT.socket.send(new Date());
								},3000)
								
							}
						}
					} else {
						alert("浏览器不支持websocket协议...");
					}
				},
				// <!--onclick事件触发-->
				chat: function() {
					// <!--获取消息,发送消息-->
					var msg = document.getElementById("msgContent");
					CHAT.socket.send(msg.value);
				},
				// <!--初始化方法-->
				connection: function(){
					let ipAddress = document.getElementById("ipAddress").value;
					if(ipAddress == undefined || ipAddress == null || ipAddress.length == 0){
						alert('請輸入ip');
						return;
					}
					CHAT.init(ipAddress);
				},
				initIp: function(i){
					document.getElementById("ipAddress").value = i;
					CHAT.connection();
				},
				initMessage: function(i){
					document.getElementById("msgContent").value = i;
				}
			};
			
			CHAT.initIp('127.0.0.1:7777/sk');
			CHAT.initMessage('{"userId": "12", "userType": "1"}');
			
		</script>
	</body>
</html>